'use strict';
// 创建db对象
const db = uniCloud.database();
// 获取 `tt_users` 集合的引用
const usersCollection = db.collection('tt_users');

let arr = [
	"https://mp-f4011f50-7780-4aca-b10a-2323b1bbdf66.cdn.bspapp.com/users/Bunny@1x.png",
	"https://mp-f4011f50-7780-4aca-b10a-2323b1bbdf66.cdn.bspapp.com/users/Elephant@1x.png",
	"https://mp-f4011f50-7780-4aca-b10a-2323b1bbdf66.cdn.bspapp.com/users/Hippo@1x.png",
	"https://mp-f4011f50-7780-4aca-b10a-2323b1bbdf66.cdn.bspapp.com/users/Lion@1x.png",
	"https://mp-f4011f50-7780-4aca-b10a-2323b1bbdf66.cdn.bspapp.com/users/Rhino@1x.png",
	"https://mp-f4011f50-7780-4aca-b10a-2323b1bbdf66.cdn.bspapp.com/users/Zebra@1x.png"
]

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)

	// 接收客户端的参数
	let {
		user,
		account,
		password
	} = event;
	if (user && account && password) {
		// 添加用户
		let id = Math.random().toString().slice(2) + "_" + (new Date().getTime().toString().slice(-6));
		let createAt = new Date().getTime()
		let index = Math.floor(Math.random() * arr.length)
		let imgUrl = arr[index]; //随机的用户头像

		// 检测一下数据表是否已经存在当前邮箱
		// 查询
		let users = await usersCollection.where({
			account: account
		}).get()
		console.log(users);
		if (users.data.length == 0) {
			// 添加
			let result = await usersCollection.add({
				user,
				account,
				password,
				id,
				createAt,
				imgUrl
			})
			return {
				code: 200,
				msg: "注册成功"
			};
		} else {
			return {
				msg: `${account} 该账号已存在。`,
				code: 1
			}
		}
	} else {
		return {
			msg: "缺少参数"
		}
	}

};